﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServerFrame
{
    public class TransModelE_D
    {
        /// <summary>
        /// 传输模型的编码
        /// </summary>
        /// <param name="target">传输模型</param>
        /// <returns>模型的字节数组</returns>
        public static byte[] TransEncode_de(object target) {
            TransModel model = target as TransModel;
            if (model == null) { return null; }


            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms);
            bw.Write(model.type);
            bw.Write(model.area);
            bw.Write(model.command);

            if (model.message != null) {
                //todo 把message序列化，并写入ms中
                byte[] value = SerializableClass.Serialization(model.message);
                bw.Write(value);
            }

            byte[] result = new byte[ms.Length];
            Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, (int)ms.Length);

            ms.Close();
            bw.Close();

            return result;
        }

        /// <summary>
        /// 传输模型解码
        /// </summary>
        /// <param name="value">传输模型的字节数组</param>
        /// <returns>传输模型</returns>
        public static object TransDecode_de(byte[] value) {
            if (value == null||value.Length<=0) { return null; }

            MemoryStream ms = new MemoryStream(value);
            BinaryReader br = new BinaryReader(ms);

            TransModel model = new TransModel();
            model.type = br.ReadByte();
            model.area = br.ReadInt32();
            model.command = br.ReadInt32();

            if (ms.CanRead) {
                byte[] v = new byte[ms.Length - ms.Position];
                //Buffer.BlockCopy(ms.GetBuffer(), (int)ms.Position, v, 0, v.Length);
                v = br.ReadBytes(v.Length);//相当于上一句

                //反序列化方法，还原
                model.message = SerializableClass.DeSerialization(v);
            }
            ms.Close();
            br.Close();

            return model;
        }
   }
}
